package mask

import (
	"fmt"
	"image"
	"sync"
)

var wg sync.WaitGroup

// GetPhotoMask 获取灰度图遮罩数据
func GetPhotoMask(img image.Image, length, width int, weight float64) (masks [][]bool, err error) {
	if weight < 0 || weight > 1 {
		return nil, fmt.Errorf("weight must between 0 and 1")
	}

	masks = make([][]bool, width)
	compare := uint32(32767 * weight)

	for i := 0; i < width; i++ {
		wg.Add(1)
		go func(img image.Image, length, lineIdx int, compare uint32) {
			defer wg.Done()
			maskArray := traversalArray(img, length, lineIdx, compare)
			masks[lineIdx] = maskArray
		}(img, length, i, compare)
	}
	wg.Wait()
	return
}

// 遍历图片
func traversalArray(img image.Image, length, lineIdx int, compare uint32) []bool {
	temp := make([]bool, 0, length)
	for j := 0; j < length; j++ {
		if r, _, _, _ := img.At(j, lineIdx).RGBA(); r <= compare {
			temp = append(temp, false)
		} else {
			temp = append(temp, true)
		}
	}
	return temp
}
